import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter/first/ui/page_web_view.dart';
import 'package:toast/toast.dart';

import '../http/Api.dart';
import 'article_item.dart';
import 'page_drawer_content.dart';

class ArticlePage extends StatefulWidget {
  const ArticlePage({super.key});

  @override
  State<ArticlePage> createState() => _ArticlePageState();
}

class _ArticlePageState extends State<ArticlePage> {
  ///滑动控制器
  ScrollController _controller = ScrollController();

  ///控制正在加载的显示
  bool _isHide = true;

  ///请求到的文章数据
  List articles = [];

  ///banner图
  List banners = [];

  ///总文章数有多少
  var totalCount = 0;

  ///分页加载，当前页码
  var curPage = 0;

  ///当前banner显示的index
  var curBannerIndex = 1;

  @override
  void initState() {
    super.initState();
    _controller.addListener(() {
      ///获得 SrollController 监听控件可以滚动的最大范围
      var maxScroll = _controller.position.maxScrollExtent;

      ///获得当前位置的像素值
      var pixels = _controller.position.pixels;

      ///当前滑动位置到达底部，同时还有更多数据
      if (maxScroll == pixels && curPage < totalCount) {
        ///加载更多
        _getArticlelist();
      }
    });

    _pullToRefresh();
  }

  _getArticlelist([bool update = true]) async {
    /// 请求成功是map，失败是null
    var data = await Api.getArticleList(curPage);
    if(data != null){
      var map = data['data'];
      var datas = map['datas'];
      ///文章总数
      totalCount = map["pageCount"];
      if(curPage == 0){
        articles.clear();
      }
      curPage++;
      articles.addAll(datas);
      if(update){
        setState(() {});
      }
    }
  }

  _getBanners([bool update = true]) async {
    var data = await Api.getBanners();
    if (data != null) {
      banners.clear();
      banners.addAll(data['data']);
      if (update) {
        setState(() {});
      }
    }
  }

  Future<void> _pullToRefresh() async {
    curPage = 0;
    Iterable<Future> futures = [_getArticlelist(),_getBanners()];
    await Future.wait(futures);
    _isHide = false;
    setState(() {});
    return;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue,
        title: Text(
          "文章",
          style: TextStyle(),
        ),
      ),
      drawer: Drawer(
        child: DrawerContent(),
      ),
      body: Stack(
        children: [
          Offstage(
            offstage: !_isHide,
            child: Center(child: CircularProgressIndicator(),),
          ),

          Offstage(
            offstage: _isHide,
              child:  RefreshIndicator(
                  onRefresh: _pullToRefresh,
                  child: ListView.builder(
                    //条目数 +1代表了banner的条目
                    itemCount: articles.length + 1,
                    //adapter条目item 视图生成方法
                    itemBuilder: (context, i) => _buildItem(i),  //被required修饰的字段必须赋值
                    controller: _controller,
                  ))
          )
        ],
      ),
    );
  }

  Widget _buildItem(int i) {
    if (i == 0) {
      //Container ：容器
      return  Container(
        //MediaQuery.of(context).size.height: 全屏幕高度
        height: MediaQuery.of(context).size.height*0.3,
        child: _bannerView(),
      );
    }
    var itemData = articles[i - 1];
    return  ArticleItem(itemData);
  }

  Widget? _bannerView() {
    List<Widget> list = banners.map((item){
      return  InkWell(
        onTap: (){
          Navigator.push(context, MaterialPageRoute(builder: (BuildContext context) {
            return Webpage(WebViewModel(item['title'],item['url']),false);
          }));
        },

        child: Image.network(item['imagePath'],fit: BoxFit.cover),
      );
    }).toList();

    return list.isNotEmpty ? Column(//Column垂直布局

      children: [
        Expanded(child: CarouselSlider(items: list, options: CarouselOptions(
            autoPlay: true,
            autoPlayAnimationDuration: Duration(milliseconds: 500),
            enlargeCenterPage: true,
            onPageChanged: (int index, CarouselPageChangedReason reason){
              curBannerIndex = index+1;
              setState(() {

              });
            }
        ))),
        Text( //指示器
          "$curBannerIndex/${list.length}",
          style: TextStyle(color: Colors.black,fontSize: 14.0),
        )
      ],
    ) : null;
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }
}
